import React, { useEffect, useState, useRef } from "react";
import {
  Table,
  Space,
  Input,
  Select,
  Form,
  Button,
  Radio,
  Flex,
  Modal,
  Pagination,
  message,
} from "antd";
import moment from "moment";
import {
  departmentGet,
  DeleteAllGet,
  DeleteGet,
  doctorAllGet,
  EditGet,
  queryGet,
} from "../../../request/xxApi";
import Department from "../../../styles/DepartmentManagement.module.css";
import "../../../assets/xxAssets/font_4791525_1loqcwtpe32h/iconfont.css";

const DepartmentManagement = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [deteleid, setdeteleid] = useState();
  const [currentPage, setCurrentPage] = useState(1);
  const [open, setOpen] = useState(false);
  const [open1, setOpen1] = useState(false);
  const [doctorAll, setDoctorAll] = useState();
  const [pageSize, setPageSize] = useState(12);
  const [total, setTotal] = useState(0); // 总记录数
  const [form] = Form.useForm();
  const [formLayout, setFormLayout] = useState("horizontal");
  const currentRecordRef = useRef();
  const inputRef = useRef();
  const [searchKeyword, setSearchKeyword] = useState("");

  useEffect(() => {
    fetchData(currentPage, pageSize, searchKeyword); // 默认查询全部数据
  }, [currentPage, pageSize, searchKeyword]);

  const fetchData = async (page, size, keyword = "") => {
    setLoading(true);
    try {
      const res = await queryGet({ page, size, name: keyword }); // 传递查询关键字给API
      const formattedData = res.data.map((item) => ({
        ...item,
        createtime: moment(item.createtime).format("YYYY-MM-DD"),
      }));
      setData(formattedData);
      setTotal(res.total);
    } catch (error) {
      console.error("Failed to fetch data:", error);
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: "科室编号",
      dataIndex: "id",
      key: "id",
      width: 200,
      align: "center",
    },
    {
      title: "科室创建时间",
      dataIndex: "createtime",
      key: "createtime",
      align: "center",
    },
    {
      title: "科室名称",
      dataIndex: "name",
      key: "name",
      align: "center",
    },
    {
      title: "科室主任",
      dataIndex: "maindoctor",
      key: "maindoctor",
      align: "center",
    },
    {
      title: "科室操作",
      key: "action",
      align: "center",
      width: 170,
      render: (text, record) => (
        <div className={Department.cellStyle}>
          <Space size="middle">
            <span
              className="iconfont icon-shanchu"
              onClick={() => deleteCLick(record.id)}
              style={{ color: "#3892F7" }}
            ></span>
            <span
              className="iconfont icon-a-bianji1"
              onClick={() => EditCLick(record)}
              style={{ color: "#3892F7" }}
            ></span>
          </Space>
        </div>
      ),
    },
  ];

  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const hasSelected = selectedRowKeys.length > 0;
  const deleteCLick = (id) => {
    setdeteleid(id);
    setOpen(true);
  };
  const onShowSizeChange = (current, size) => {
    setPageSize(size);
    setCurrentPage(1); // 当改变每页显示条数时，通常回到第一页
    fetchData(1, size, searchKeyword);
  };

  const handleOk = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      setOpen(false);
    }, 1000);
  };
  const handleOkClick = () => {
    setOpen1(false); // 关闭 Modal
  };

  const handleCancel = () => {
    DeleteGet({ id: deteleid }).then((res) => {
      if (res.code === 1) {
        message.success("成功删除");
        fetchData(currentPage, pageSize, searchKeyword);
      }
    });
    setOpen(false);
  };
  const handleCancelClick = () => {
    setOpen1(false); // 关闭 Modal
    form.resetFields(); // 重置表单
  };
  //修改方法
  const EditCLick = (record) => {
    doctorAllGet().then((res) => {
      const doctors = res.data.map((doctor) => ({
        label: doctor.name,
        value: doctor.name,
      }));
      setDoctorAll(doctors);
      setOpen1(true); // 打开编辑模态框
      form.setFieldsValue({
        name: record.name,
        maindoctor: record.maindoctor,
        createtime: record.createtime,
        id: record.id,
      });
    });
  };
  //确认修改
  const onFormFinish = (values) => {
    EditGet(values).then((res) => {
      if (res.code === 1) {
        message.success("修改成功");
      }
    });
    updateDepartment(values);
    setOpen1(false);
  };
  const updateDepartment = (updatedValues) => {};

  const handleSearch = () => {
    const value = inputRef.current.input.value;
    setSearchKeyword(value); // 更新查询关键字状态
    setCurrentPage(1); // 重置到第一页
    fetchData(1, pageSize, value); // 执行查询
  };

  // useEffect 将正确地在 currentRecord 变化时打印最新的值

  const handlePageChange = (page) => {
    setCurrentPage(page);
    fetchData(page, pageSize, searchKeyword); // 执行分页查询，保持查询关键字不变
  };

  const handleDeleteSelected = async () => {
    if (selectedRowKeys.length === 0) {
      // 如果没有选中的项，则不执行任何操作
      message.warning("请选择要删除的项");
      return;
    }
    setLoading(true);
    try {
      // 调用封装好的批量删除请求方法
      const response = await DeleteAllGet({ ids: selectedRowKeys });
      if (response.code === 1) {
        // 处理错误情况
        message.success("批量删除成功");
        setSelectedRowKeys([]); // 清空选中的项
        setCurrentPage(1); // 重置到第一页
        fetchData(1, pageSize); // 重新加载数据
      } else {
        // 删除成功的处理
      }
    } catch (error) {}
  };

  return (
    <>
      <div className={Department.box}>
        <Modal
          open={open}
          title="系统提示"
          onCancel={handleCancel}
          footer={null}
        >
          <p className={Department.modal_text}>
            您正在进行科室删除操作，此操作不可逆，确定要删除对应科室吗？
          </p>
          <div className={Department.modal_btn_box}>
            <Button
              key="back"
              className={Department.modal_btn}
              onClick={handleCancel}
            >
              确定删除
            </Button>
            <Button
              key="submit"
              className={Department.modal_btn}
              type="primary"
              loading={loading}
              onClick={handleOk}
            >
              取消
            </Button>
          </div>
        </Modal>
        <Modal
          open={open1}
          title="编辑科室"
          onOk={handleOkClick}
          onCancel={handleCancelClick}
          footer={null}
        >
          <Form
            onFinish={onFormFinish}
            layout={formLayout}
            form={form}
            style={{
              marginTop: "20px",
              maxWidth: formLayout === "inline" ? "none" : 600,
            }}
          >
            <Form.Item name="name" label="科室名称">
              <Input
                placeholder={
                  currentRecordRef.current ? currentRecordRef.current.name : ""
                }
              />
            </Form.Item>
            <Form.Item name="maindoctor" label="科室主任">
              <Select
                placeholder="全部医生"
                className={Department.director_Select}
                options={doctorAll}
              />
            </Form.Item>
            <Form.Item name="createtime" label="创建时间">
              <Input
                value={
                  currentRecordRef.current
                    ? currentRecordRef.current.createtime
                    : ""
                }
                disabled
              />
            </Form.Item>
            <Form.Item name="id" label="科室编号">
              <Input
                disabled
                value={
                  currentRecordRef.current ? currentRecordRef.current.id : ""
                }
              />
            </Form.Item>
            <Form.Item>
              <div className={Department.director_btn_box}>
                <Button
                  className={Department.modal_btn}
                  type="primary"
                  htmlType="submit"
                >
                  确认
                </Button>
                <Button
                  key="submit"
                  className={Department.modal_btnn}
                  loading={loading}
                  onClick={handleOkClick}
                >
                  取消
                </Button>
              </div>
            </Form.Item>
          </Form>
        </Modal>

        <Flex gap="middle" vertical>
          <Flex align="center" gap="middle">
            <div className={Department.title}>
              <div className={Department.title_left}>
                <div className={Department.title_name}>科室名称</div>
                <div>
                  <Input ref={inputRef} placeholder="输入科室名称" />
                </div>
                <Button
                  onClick={handleSearch}
                  type="primary"
                  className={Department.title_left_btn}
                >
                  <span
                    className="iconfont icon-ic_search24px"
                    style={{ color: "white" }}
                  ></span>
                  查询
                </Button>
              </div>
              <Button
                onClick={handleDeleteSelected}
                disabled={!hasSelected}
                loading={loading}
                type="dashed"
                danger
              >
                删除选中
              </Button>
            </div>
          </Flex>
          <Table
            bordered
            size="small"
            rowSelection={rowSelection}
            dataSource={data}
            pagination={false}
            rowClassName={Department.customTableCell}
            className={Department.customTableCell}
            rowKey="id"
          >
            {columns.map((col) => (
              <Table.Column
                className={Department.customTableCell}
                key={col.key}
                title={col.title}
                dataIndex={col.dataIndex}
                width={col.width}
                align={col.align}
                render={col.render}
              />
            ))}
          </Table>
          <div className={Department.paging_box}>
            共{total}条
            <Pagination
              size="small"
              className={Department.paging}
              current={currentPage}
              pageSize={pageSize}
              total={total}
              onChange={handlePageChange}
              onShowSizeChange={onShowSizeChange}
              showSizeChanger
              showQuickJumper
              pageSizeOptions={["5", "10"]}
              defaultCurrent={2}
            />
          </div>
        </Flex>
      </div>
    </>
  );
};

export default DepartmentManagement;
